package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 用户登录
     * @param adUserDTO
     * @return
     */
    @Override
    public ResponseResult login(AdUserDTO adUserDTO) {
        String adUserDTOName = adUserDTO.getName();
        String adUserDTOPassword = adUserDTO.getPassword();

        if(StringUtil.isBlank(adUserDTOName) || StringUtil.isBlank(adUserDTOPassword)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //1.检查用户是否存在
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDTOName));
        if(adUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //2.检查密码是否正确 需要先将用户输入的密码加盐加密后与数据库密码进行比对
        String salt = adUser.getSalt(); //盐
        String adUserPwd = DigestUtils.md5DigestAsHex((adUserDTOPassword + salt).getBytes());
        if(! adUserPwd.equals(adUser.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }
        //3.检查用户状态是否有效
        if(adUser.getStatus() != AdminConstants.PASS_AUTH.intValue()){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //4.修改最近登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //5.颁发token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //用户信息返回vo
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,adUserVO);
        //返回结果
        Map map = new HashMap();
        map.put("token",token);
        map.put("user",adUserVO);

        return ResponseResult.okResult(map);
    }
}
